<template>
  <div>
    <el-checkbox-group v-model="roleIds">
      <el-checkbox
        v-for="obj in list"
        :key="obj.id"
        :label="obj.id"
      >{{ obj.name }}
      </el-checkbox>
    </el-checkbox-group>
    <div style="margin-top: 20px; text-align: right">
      <el-button type="primary" @click="saveFn">确定</el-button>
      <el-button @click="closeDialog">取消</el-button>
    </div>
  </div>
</template>
<script>
import { getUserDetailById } from '@/api/user'
import { getRoleListAPI } from '@/api/setting'
import { assignRolesAPI } from '@/api/employees'
export default {
  props: {
    // 点击用户的id
    userId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      roleIds: [], // 这里是默认选中的权限列表
      list: []
    }
  },
  // 监听userId的变化,如果有变化就重新发送请求,回填数据
  // watch: {
  //   userId(newVal, oldVal) {
  //     this.loadRoleIds()
  //   }
  // },
  created() {
    // 请求数据,铺设页面
    this.loadRoles()
    // 数据回填
    this.loadRoleIds()
  },
  methods: {
    // 数据回填需要请求的api
    async loadRoleIds() {
      const res = await getUserDetailById(this.userId)
      console.log('根据id获取用户的详情', res)
      this.roleIds = res.roleIds
    },
    async loadRoles() {
      // 弹窗出现的时候,请求数据
      const res = await getRoleListAPI({ page: 1, pagesize: 100 })
      console.log(res)
      this.list = res.rows
    },
    // 点击确定,调用的方法
    async saveFn() {
      const res = await assignRolesAPI({
        id: this.userId,
        roleIds: this.roleIds
      })
      console.log('确定之后返回的是', res)
      // 提示用户
      this.$message.success('分配成功')
      // 关闭弹窗
      this.$emit('closeRole')
    },
    closeDialog() {
      this.$emit('closeRole')
      // 关闭弹窗,清空数据
      this.roleIds = []
    }
  }
}
</script>
